#pragma once

#include "Socket.hpp"
#include <iostream>
#include <pthread.h>
#include <functional>
#include <string>
class TcpServer;
using namespace std;
using func_t = function<string(string&request)>;
class ThreadData
{
public:
    ThreadData(TcpServer *tcp_this, Net_Work::Socket *sockp) : _this(tcp_this), _sockp(sockp)
    {
    }

public:
    TcpServer *_this;
    Net_Work::Socket *_sockp;
};
class TcpServer
{
public:
    TcpServer(func_t handler_request, uint16_t port)
    :_handler_request(handler_request)
    ,_port(port)
    ,_listensocket(new Net_Work::TcpSocket())
    {
        _listensocket->BuildListenSocketMethod(_port, Net_Work::backlog);
    };
    static void *ThreadRun(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        string inbufferstream;
        while (true)
        {
            bool ok = true;
            if (!td->_sockp->Recv(&inbufferstream, 1024))
            {
                break;
            }
            string send_string = td->_this->_handler_request(inbufferstream);
            if (ok)
            {
                if (!send_string.empty())
                {
                    td->_sockp->Send(send_string);
                }
            }
             else
            {
                break;
            }
        }
        td->_sockp->CloseSocket();
        delete td->_sockp;
        delete td;
        return nullptr;
    }
    
    void Loop()
    {
        while (true)
        {
            string peerip;
            uint16_t peerport;
            Net_Work::Socket *newsock = _listensocket->AcceptConnection(&peerip, &peerport);
            if (newsock == nullptr)
            {
            cout<<"失败"<<endl;
                continue;
            }
            std::cout << "获取一个新连接, sockfd: " << newsock->GetSockFd() << " client info: " << peerip << ":" << peerport << std::endl;
            pthread_t tid;
            ThreadData *td = new ThreadData(this, newsock);
            pthread_create(&tid, nullptr, ThreadRun, td);
        }
    }
    ~TcpServer(){};

private:
    int _port;
    Net_Work::Socket *_listensocket;

public:
    func_t _handler_request;
};